package modules.service;

import java.util.List;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import modules.common.GenUtils;
import modules.common.StringUtils;
import modules.dao.GenDataBaseDictDao;
import modules.model.GenConfig;
import modules.model.GenTable;
import modules.model.GenTableColumn;
import modules.model.GenTemplate;

/**
 * 业务表Service
 * @author Ruoli
 * @version 2017-08-30
 */
@Service
@Transactional(readOnly = true)
public class GeneratorService {
	@Autowired
	private GenDataBaseDictDao genDataBaseDictDao;
	
	
	/**
	 * 获取物理数据表列表
	 * @param genTable
	 * @return
	 */
	public List<GenTable> findTableListFormDb(GenTable genTable){
		List<GenTable> genTableList=genDataBaseDictDao.findTableList(genTable);
		return genTableList;
	}
	
	/**
	 * 获取物理数据表列表
	 * @param genTable
	 * @return
	 */
	public GenTable getTableFormDb(GenTable genTable){
		// 如果有表名，则获取物理表
		if (StringUtils.isNotBlank(genTable.getName())){
			List<GenTable> list = genDataBaseDictDao.findTableList(genTable);
			if (list.size() > 0){
				// 如果是新增，初始化表属性
				if (StringUtils.isBlank(genTable.getId())){
					genTable = list.get(0);
					// 设置字段说明
					if (StringUtils.isBlank(genTable.getComments())){
						genTable.setComments(genTable.getName());
					}
					genTable.setClassName(StringUtils.toCapitalizeCamelCase(genTable.getName()));
				}
				// 添加新列
				List<GenTableColumn> columnList = genDataBaseDictDao.findTableColumnList(genTable);
				for (GenTableColumn column : columnList){
					boolean b = false;
					for (GenTableColumn e : genTable.getColumnList()){
						if (e.getName().equals(column.getName())){
							b = true;
						}
					}
					if (!b){
						genTable.getColumnList().add(column);
					}
				}
				// 删除已删除的列
				for (GenTableColumn e : genTable.getColumnList()){
					boolean b = false;
					for (GenTableColumn column : columnList){
						if (column.getName().equals(e.getName())){
							b = true;
						}
					}
					if (!b){
						e.setDelFlag("1");
					}
				}
				// 获取主键
				genTable.setPkList(genDataBaseDictDao.findTablePK(genTable));
				// 初始化列属性字段
				GenUtils.initColumnField(genTable);
			}
		}
		return genTable;
	}
	public String buildCode(GenTable genTable){
		StringBuilder result = new StringBuilder();
		// 获取所有代码模板
		GenConfig config = GenUtils.getConfig();
		// 获取模板列表
		List<GenTemplate> templateList = GenUtils.getTemplateList(config,"dao", false);
		// 生成主表模板代码
		Map<String, Object> model = GenUtils.getDataModel(genTable);
		for (GenTemplate tpl : templateList){
			result.append(GenUtils.generateToFile(tpl, model));
		}
		return result.toString();
	}
}
